from datetime import datetime

from flask import request

from flask_jwt_extended import jwt_required
from flask_restx import Namespace, Resource, fields
from app1 import db

from app1.models import Zbfwbperm

# 创建 Flask-RESTx 命名空间
ns_perm = Namespace('ns_perm', description='Perm operations')

# 使用 Flask-RESTx 定义用户数据模型
perm_model = ns_perm.model('Zbfwbperm', {
    'id': fields.Integer(required=True, description='The perm unique identifier'),
    'per_name': fields.String(required=True, description='per_name'),
    'perm_code': fields.Integer(required=True, description='perm_code'),
    'perm_op': fields.String(required=True, description='perm_op'),
    'perm_ob': fields.String(required=True, description='perm_ob'),
    'create_time': fields.DateTime(description='Perm creation time'),
    'update_time': fields.DateTime(description='Perm update time')
})

# 定义外层的响应模型
response_perm_model = ns_perm.model('Response_Perm', {
    'message': fields.Nested(ns_perm.model('Message_Perm', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.List(fields.Nested(perm_model))
    }))
})

# 使用 Flask-RESTx 定义用户数据模型
perm_query_model = ns_perm.model('Zbfwbperm', {
    'id': fields.Integer(required=True, description='The role unique identifier', default=0),
    'per_name': fields.String(required=True, description='Role name', default=""),
    'perm_code': fields.Integer(required=True, description='Role tittle', default=0),
    'perm_op': fields.String(required=True, description='perm_op', default=""),
    'perm_ob': fields.String(required=True, description='perm_ob', default=""),
})

# 使用 Flask-RESTx 定义用户数据模型
perm_add_model = ns_perm.model('Zbfwbpermadd', {
    'per_name': fields.String(required=True, description='Role name', default=""),
    'perm_code': fields.Integer(required=True, description='Role tittle', default=0),
    'perm_op': fields.String(required=True, description='perm_op', default=""),
    'perm_ob': fields.String(required=True, description='perm_ob', default=""),
})

# 使用 Flask-RESTx 定义用户数据模型
perm_delete_model = ns_perm.model('Zbfwbpermdelete', {
    'perm_code': fields.Integer(required=True, description='Role tittle', default=0),
})

# 使用 Flask-RESTx 定义用户数据模型
perm_upd_model = ns_perm.model('Zbfwbpermupd', {
    'per_name': fields.String(required=True, description='Role name', default=""),
    'perm_code': fields.Integer(required=True, description='Role tittle', default=0),
    'perm_op': fields.String(required=True, description='perm_op', default=""),
    'perm_ob': fields.String(required=True, description='perm_ob', default=""),
})


# 查询
@ns_perm.route('/perm_list')
class PermResource(Resource):
    # @jwt_required()
    @ns_perm.expect(perm_query_model)
    @ns_perm.marshal_with(response_perm_model)
    def post(self):
        """根据输入的id 或者 per_name 或者 perm_code 或者 perm_op 或者 perm_ob匹配查询，如果字符串输入值为空或者数字为0，则指匹配全部"""
        data = request.get_json()

        # 构建查询条件
        query = Zbfwbperm.query
        if 'id' in data and data['id'] != 0:
            query = query.filter_by(id=data['id'])
        if 'per_name' in data and data['per_name'] != "":
            query = query.filter(Zbfwbperm.per_name.like(f"%{data['per_name']}%"))
        if 'perm_code' in data and data['perm_code'] != 0:
            query = query.filter_by(perm_code=data['perm_code'])
        if 'perm_op' in data and data['perm_op'] != "":
            query = query.filter(Zbfwbperm.perm_op.like(f"%{data['perm_op']}%"))
        if 'perm_ob' in data and data['perm_ob'] != "":
            query = query.filter(Zbfwbperm.perm_ob.like(f"%{data['perm_ob']}%"))

        perms = query.all()

        return {
            'message': {
                'result': 0,
                'result_text': '查询成功',
                'count': len(perms),
                'data': [perm.to_dict() for perm in perms]
            }
        }


# 新增
@ns_perm.route('/perm_create')
class PermAddResource(Resource):
    # @jwt_required()
    @ns_perm.expect(perm_add_model)
    @ns_perm.marshal_with(response_perm_model)
    def post(self):
        """ id 为当前总记录加1，name 和 title 需要输入"""
        data = request.get_json()

        # 检查所有必填字段是否为空
        required_fields = ['per_name', 'perm_code', 'perm_op', 'perm_ob']
        missing_fields = [field for field in required_fields if not data.get(field)]

        if missing_fields:
            return {
                'message': {
                    'result': 1,
                    'result_text': f'以下字段不能为空: {", ".join(missing_fields)}',
                    'count': 0,
                    'data': []
                }
            }, 400

        # 检查权限名是否已存在
        if Zbfwbperm.query.filter_by(per_name=data['per_name']).first():
            return {
                'message': {
                    'result': 1,
                    'result_text': f'权限名称"{data["per_name"]}"已存在',
                    'count': 0,
                    'data': []
                }
            }, 400

        # 检查权限码是否已存在
        if Zbfwbperm.query.filter_by(perm_code=data['perm_code']).first():
            return {
                'message': {
                    'result': 1,
                    'result_text': f'权限码"{data["perm_code"]}"已存在',
                    'count': 0,
                    'data': []
                }
            }, 400

        # 创建新权限
        new_perm = Zbfwbperm(
            per_name=data['per_name'],
            perm_code=data['perm_code'],
            perm_op=data['perm_op'],
            perm_ob=data['perm_ob']
        )

        try:
            db.session.add(new_perm)
            db.session.commit()

            return {
                'message': {
                    'result': 0,
                    'result_text': '权限创建成功',
                    'count': 1,
                    'data': [new_perm.to_dict()]
                }
            }, 201
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'创建权限时发生错误: {str(e)}',
                    'count': 0,
                    'data': []
                }
            }, 500


# 删除
@ns_perm.route('/perm_delete')
class PermDeleteResource(Resource):
    # @jwt_required()
    @ns_perm.expect(perm_delete_model)
    @ns_perm.marshal_with(response_perm_model)
    def post(self):
        """Delete a perm"""
        data = request.get_json()

        # 查找要删除的权限
        perm = Zbfwbperm.query.filter_by(perm_code=data['perm_code']).first()
        if not perm:
            return {
                'message': {
                    'result': 1,
                    'result_text': '权限不存在',
                    'count': 0,
                    'data': []
                }
            }, 404

        db.session.delete(perm)
        db.session.commit()

        return {
            'message': {
                'result': 0,
                'result_text': '权限删除成功',
                'count': 1,
                'data': [perm.to_dict()]
            }
        }


# 修改
@ns_perm.route('/perm_updt')
class PermUpdateResource(Resource):
    # @jwt_required()
    @ns_perm.expect(perm_upd_model)
    @ns_perm.marshal_with(response_perm_model)
    def post(self):
        """Update a perm"""
        data = request.get_json()

        # 检查所有必填字段是否为空
        required_fields = ['per_name', 'perm_code', 'perm_op', 'perm_ob']
        missing_fields = [field for field in required_fields if not data.get(field)]

        if missing_fields:
            return {
                'message': {
                    'result': 1,
                    'result_text': f'以下字段不能为空: {", ".join(missing_fields)}',
                    'count': 0,
                    'data': []
                }
            }, 400

        # 查找要更新的权限
        perm = Zbfwbperm.query.filter_by(perm_code=data['perm_code']).first()
        if not perm:
            return {
                'message': {
                    'result': 1,
                    'result_text': '权限不存在',
                    'count': 0,
                    'data': []
                }
            }, 404

        # 检查权限名是否已存在（排除当前记录）
        existing_perm = Zbfwbperm.query.filter(
            Zbfwbperm.per_name == data['per_name'],
            Zbfwbperm.perm_code != data['perm_code']  # 排除当前记录
        ).first()

        if existing_perm:
            return {
                'message': {
                    'result': 1,
                    'result_text': f'权限名称"{data["per_name"]}"已存在',
                    'count': 0,
                    'data': []
                }
            }, 400

        try:
            # 更新权限信息
            perm.per_name = data['per_name']
            perm.perm_op = data['perm_op']
            perm.perm_ob = data['perm_ob']
            perm.update_time = datetime.utcnow()

            db.session.commit()

            return {
                'message': {
                    'result': 0,
                    'result_text': '权限更新成功',
                    'count': 1,
                    'data': [perm.to_dict()]
                }
            }
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'更新权限时发生错误: {str(e)}',
                    'count': 0,
                    'data': []
                }
            }, 500
